package com.gupaoedu.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;


public class ConnectionDemo {

    public static void main(String[] args) {
        try {
            final CountDownLatch countDownLatch=new CountDownLatch(1);
          ZooKeeper zooKeeper=  new ZooKeeper("192.168.255.128:2181," + "192.168.255.131:2181,192.168.255.132:2181"


                           ,
                            4000, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            if(Event.KeeperState.SyncConnected==event.getState()){
                                //如果收到了服务端的响应事件，连接成功
                                countDownLatch.countDown();
                            }
                        }
                    });
            countDownLatch.await();
            System.out.println(zooKeeper.getState());//CONNECTED

            //添加节点  acl
            /**
             *  CreateMode.PERSISTENT 设置为持久化节点
             *  ZooDefs.Ids.OPEN_ACL_UNSAFE  开放式acl 设置权限
             *  "/zk-persis-mic"  节点路径
             *  "0".getBytes()    value值
             */
            zooKeeper.create("/zk-persis-mic","0".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            Thread.sleep(1000);
            Stat stat=new Stat();

            //得到当前节点的值
            /***
             * cZxid = 0x15
             ctime = Sun Nov 18 16:41:54 CST 2018
             mZxid = 0x15
             mtime = Sun Nov 18 16:41:54 CST 2018
             pZxid = 0x26
             cversion = 17
             dataVersion = 0
             aclVersion = 0
             ephemeralOwner = 0x0
             dataLength = 3
             numChildren = 17
             */
            byte[] bytes=zooKeeper.getData("/zk-persis-mic",null,stat);
            //得到当前节点的值
            System.out.println(new String( bytes));

            //修改节点值
            zooKeeper.setData("/zk-persis-mic","1".getBytes(),stat.getVersion());

            //得到当前节点的值
            byte[] bytes1=zooKeeper.getData("/zk-persis-mic",null,stat);
            System.out.println(new String(bytes1));

     //       zooKeeper.delete("/zk-persis-mic",stat.getVersion());

            zooKeeper.close();

            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }
}
